package com.yc154.springmvc1.demos.web;


import com.yc154.springmvc1.demos.biz.BizException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

@RestControllerAdvice
//@ControllerAdvice
public class ExHandler {

    @ExceptionHandler(BizException.class)
    public Object bizExceptionHandle(BizException e,
                                     HttpServletRequest request){
        String accept = request.getHeader("Accept");
        if(accept.contains("json")){
            // JSON
            return Map.of("code",0,
                    "msg",e.getMessage(),
                    "data",e.getData());
        } else {
            // 页面跳转
            ModelAndView mav = new ModelAndView();
            mav.addObject("msg",e.getMessage());
            mav.addObject("data",e.getData());
            mav.setViewName("error");
            return mav;
        }
    }

    public Object runtimeExceptionHandle(RuntimeException e,
                                     HttpServletRequest request){
        // 打印 TODO 通知维护人员和开发人员(发短信,发邮件)
        e.printStackTrace();
        String accept = request.getHeader("Accept");
        if(accept.contains("json")){
            // JSON
            return Map.of("code",0,
                    "msg","系统繁忙,请联系客服");
        } else {
            // 页面跳转
            ModelAndView mav = new ModelAndView();
            mav.addObject("msg","系统繁忙,请联系客服");
            mav.setViewName("error");
            return mav;
        }
    }

}
